package com.czl.module_storehouse.mvp.model;

import com.czl.base.data.bean.tengyun.ProductBean;
import com.czl.base.data.net.RetrofitClient;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_storehouse.api.ApiService;

import org.json.JSONObject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @author by xubin,
 * @date on 2022/2/11.
 * PS: Not easy to write code, please indicate.
 */
public class ProductModel extends BasicDataModel {

    public Observable<HttpResponse<ProductBean>> getProductInfo(int productId) {
        JSONObject object = new JSONObject();
        try {
            object.put("productId", productId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String json = object.toString();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        return RetrofitClient.getInstance().create(ApiService.class).getProductInfo2(RequestBody.create(mediaType, json));
    }

    public Observable<HttpResponse<ProductBean>> getProductUseInfo(int productId) {
        JSONObject object = new JSONObject();
        try {
            object.put("productId", productId);
            object.put("storehouseId", getStorehouseId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RetrofitClient.getInstance().create(ApiService.class).getProductUseInfo(createBody(object));
    }

    public Observable<HttpResponse<ProductBean>> getProductInfoByCode(String productCode) {
        JSONObject object = new JSONObject();
        try {
            object.put("productCode", productCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String json = object.toString();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        return RetrofitClient.getInstance().create(ApiService.class).getProductInfoByCode(RequestBody.create(mediaType, json));
    }

    public Observable<HttpResponse<ProductBean>> getProductUseInfoByCode(String productCode) {
        return getProductInfoByCode(productCode)
                .flatMap((Function<HttpResponse<ProductBean>, ObservableSource<HttpResponse<ProductBean>>>) productBeanHttpResponse -> {
                    if (productBeanHttpResponse.isSuccess() && productBeanHttpResponse.getData() != null &&
                            productBeanHttpResponse.getData().getProductId() != null) {
                        return getProductUseInfo(productBeanHttpResponse.getData().getProductId());
                    }
                    return Observable.error(new Exception(productBeanHttpResponse.getMsg()));
                });
    }
}
